var App = {
	serverUrl : parseAppProperty("#[serverUrl]#","http://127.0.0.1:8080/"),
	oauthUrl : "#[oauthUrl]#",
	sessionId : "",
	isLogEnable : ("true" === "#[isLogEnable]#"),
	isNewConsole: ("true" === "#[isNewConsole]#"),
	cacheEnable : ("true" === "#[cacheEnable]#"),
	previewUrlPrefix:"#[previewUrlPrefix]#",
	bmwServiceUrl:"#[bmwServiceUrl]#",
	urlParam:"",
};



/**
@value 要替换的值
@def 默认值
*/
function parseAppProperty(value, def){
	var reg=/#\[[\w,/.]+\]#/;
	if(value.search(reg)<0){
		// no match
		return value;
	}else{
		// match
		return def;
	}
};
/**
 * 全局活动信息定义类型;
 * http://127.0.0.1:8080/
 */
var ACTIVITY_TYPE = {
	"PAY_TO_MEMBER" : {
		"val" : "21",
		"enum" : "PAY_TO_MEMBER",
		"DISCOUNTS_INFO" : "",
		"des" : "支付会员招募",
		"provideMode" : "",
		"isHaveChannel" : "yes",
		"activityObject" : "所有顾客",
		"isSupportKouBeiKe" : "no"
	},
	"SEND_FOR_CONSUME" : {
		"val" : "22",
		"enum" : "SEND_FOR_CONSUME",
		"DISCOUNTS_INFO" : "",
		"des" : "消费送券",
		"provideMode" : "消费后自动发放至会员卡券包",
		"isHaveChannel" : "no",
		"activityObject" : "所有顾客",
		"isSupportKouBeiKe" : "no"
	},
	"NCREASE_CONSUMPTION" : {
		"val" : "23",
		"enum" : "NCREASE_CONSUMPTION",
		"DISCOUNTS_INFO" : "",
		"des" : "交易额提升",
		"provideMode" : "",
		"isHaveChannel" : "yes",
		"activityObject" : "",
		"isSupportKouBeiKe" : "no"
	},
	"SCAN_CODE" : {
		"val" : "25",
		"enum" : "SCAN_CODE",
		"DISCOUNTS_INFO" : "",
		"des" : "扫码送券",
		"provideMode" : "顾客扫码后领取",
		"isHaveChannel" : "yes",
		"activityObject" : "所有顾客",
		"isSupportKouBeiKe" : "yes"
	},
	"HOLIDAY_MARKETING" : {
		"val" : "26",
		"enum" : "HOLIDAY_MARKETING",
		"DISCOUNTS_INFO" : "专属优惠,开心过节",
		"des" : "节日营销",
		"provideMode" : "会员在投放渠道领取",
		"isHaveChannel" : "yes",
		"activityObject" : "所有会员",
		"isSupportKouBeiKe" : "yes"
	},
	"TIME_PERIOD_MARKETING" : {
		"val" : "27",
		"enum" : "TIME_PERIOD_MARKETING",
		"DISCOUNTS_INFO" : "",
		"des" : "时段营销",
		"provideMode" : "",
		"isHaveChannel" : "yes",
		"activityObject" : "",
		"isSupportKouBeiKe" : "no"
	},
	"BIRTHDAY_MARKETING" : {
		"val" : "28",
		"enum" : "BIRTHDAY_MARKETING",
		"DISCOUNTS_INFO" : "",
		"des" : "生日营销",
		"provideMode" : "",
		"isHaveChannel" : "yes",
		"activityObject" : "",
		"isSupportKouBeiKe" : "no"
	},
	"INCREASE_CONSUM_TIMES" : {
		"val" : "29",
		"enum" : "INCREASE_CONSUM_TIMES",
		"DISCOUNTS_INFO" : "",
		"des" : "消费频次提升",
		"provideMode" : "",
		"isHaveChannel" : "yes",
		"activityObject" : "",
		"isSupportKouBeiKe" : "no"
	},
	"CUSTOMIZE_ACTIVITY" : {
		"val" : "30",
		"enum" : "CUSTOMIZE_ACTIVITY",
		"DISCOUNTS_INFO" : "",
		"des" : "自定义人群活动",
		"provideMode" : "会员在投放渠道领取",
		"isHaveChannel" : "yes",
		"activityObject" : "自定义人群活动",
		"isSupportKouBeiKe" : "no"
	},
	"NOT_PATRONAGE_MORETHAN_30DAYS" : {
		"val" : "31",
		"enum" : "NOT_PATRONAGE_MORETHAN_30DAYS",
		"DISCOUNTS_INFO" : "",
		"des" : "30天以上未到店消费会员",
		"provideMode" : "",
		"isHaveChannel" : "yes",
		"activityObject" : "",
		"isSupportKouBeiKe" : "no"
	},
	"LESSTHAN_XTIMES_LAST_30DAYS" : {
		"val" : "32",
		"enum" : "LESSTHAN_XTIMES_LAST_30DAYS",
		"DISCOUNTS_INFO" : "",
		"des" : "近30天低于x次消费的会员",
		"provideMode" : "",
		"isHaveChannel" : "yes",
		"activityObject" : "",
		"isSupportKouBeiKe" : "no"
	},
	"BIRTHDAY_CURRENT_MONTH" : {
		"val" : "33",
		"enum" : "BIRTHDAY_CURRENT_MONTH",
		"DISCOUNTS_INFO" : "",
		"des" : "本月生日会员",
		"provideMode" : "",
		"isHaveChannel" : "yes",
		"activityObject" : "",
		"isSupportKouBeiKe" : "no"
	},
	"BIG_GIFT_PACKAGE" : {
		"val" : "34",
		"enum" : "BIG_GIFT_PACKAGE",
		"DISCOUNTS_INFO" : "",
		"des" : "会员大礼包",
		"provideMode" : "消费后自动发放至会员卡券包",
		"isHaveChannel" : "no",
		"activityObject" : "所有顾客",
		"isSupportKouBeiKe" : "no"
	},
	"LATTER_SEND" : {
		"val" : "35",
		"enum" : "LATTER_SEND",
		"DISCOUNTS_INFO" : "",
		"des" : "消费送券",
		"provideMode" : "消费后自动发放至会员卡券包",
		"isHaveChannel" : "no",
		"activityObject" : "所有顾客",
		"isSupportKouBeiKe" : "no"
	},
	"LIGHT_LOST_CLIENT" : {
		"val" : "36",
		"enum" : "LIGHTLOSTCLIENT",
		"DISCOUNTS_INFO" : "亲,好久不见哦",
		"des" : "轻度流失会员",
		"provideMode" : "会员在投放渠道领取",
		"isHaveChannel" : "yes",
		"activityObject" : "x天未到店消费会员",
		"isSupportKouBeiKe" : "yes"
	},
	"PASSWORD_PREFERENTIAL" : {
		"val" : "37",
		"enum" : "PASSWORD_PREFERENTIAL",
		"DISCOUNTS_INFO" : "",
		"des" : "口令优惠",
		"provideMode" : "顾客在支付宝输入口令后领取",
		"isHaveChannel" : "no",
		"activityObject" : "所有顾客",
		"isSupportKouBeiKe" : "no"
	},
	"NEXT_MONTH_BIRTHDAY" : {
		"val" : "38",
		"enum" : "NEXTMONTHBIRTHDAY",
		"DISCOUNTS_INFO" : "生日你最大,优惠请收下",
		"des" : "生日会员",
		"provideMode" : "会员在投放渠道领取",
		"isHaveChannel" : "yes",
		"activityObject" : "生日会员",
		"isSupportKouBeiKe" : "yes"
	},
	"LOW_CONSUME_CLIENT" : {
		"val" : "39",
		"enum" : "LOWCONSUMECLIENT",
		"DISCOUNTS_INFO" : "您消费,我优惠",
		"des" : "低消费常客",
		"provideMode" : "会员在投放渠道领取",
		"isHaveChannel" : "yes",
		"activityObject" : "低消费常客",
		"isSupportKouBeiKe" : "yes"
	},
	"LIVE_NEARBY" : {
		"val" : "40",
		"enum" : "LIVENEARBY",
		"DISCOUNTS_INFO" : "专属优惠送给附近的你",
		"des" : "住在门店附近的会员",
		"provideMode" : "会员在投放渠道领取",
		"isHaveChannel" : "yes",
		"activityObject" : "住在门店附近的会员",
		"isSupportKouBeiKe" : "yes"
	},
	"HIGH_CONSUME_FIT" : {
		"val" : "41",
		"enum" : "HIGHCONSUMEFIT",
		"DISCOUNTS_INFO" : "给你我的爱,大爷你常来",
		"des" : "高消费散客",
		"provideMode" : "会员在投放渠道领取",
		"isHaveChannel" : "yes",
		"activityObject" : "高消费散客",
		"isSupportKouBeiKe" : "yes"
	},
	"LOYAL_CLIENT" : {
		"val" : "42",
		"enum" : "LOYALCLIENT",
		"DISCOUNTS_INFO" : "别说话,我给你的优惠最大",
		"des" : "忠实会员",
		"provideMode" : "会员在投放渠道领取",
		"isHaveChannel" : "yes",
		"activityObject" : "忠实会员",
		"isSupportKouBeiKe" : "yes"
	},
	"CUSTOMIZE_CROWD_GROUP" : {
		"val" : "43",
		"enum" : "CUSTOMIZE_CROWD_GROUP",
		"DISCOUNTS_INFO" : "",
		"des" : "自定义人群活动",
		"provideMode" : "会员在投放渠道领取",
		"isHaveChannel" : "yes",
		"activityObject" : "自定义人群活动",
		"isSupportKouBeiKe" : "yes"
	},
	"POINT_CARD" : {
		"val" : "44",
		"enum" : "POINT_CARD",
		"DISCOUNTS_INFO" : "",
		"des" : "集点卡",
		"provideMode" : "集点",
		"isHaveChannel" : "no",
		"activityObject" : "集点卡活动",
		"isSupportKouBeiKe" : "no"
	},
	"NEW_MEMBER" : {
		"val" : "46",
		"enum" : "NEW_MEMBER",
		"DISCOUNTS_INFO" : "新人领券,快快领取",
		"des" : "新会员招募",
		"provideMode" : "顾客在投放渠道领券",
		"isHaveChannel" : "yes",
		"activityObject" : "从未到店消费顾客",
		"isSupportKouBeiKe" : "yes"
	},
	"ITEM_MARKET":{
		"val" : "47",
		"enum" : "ITEM_MARKET",
		"DISCOUNTS_INFO" : "单品营销",
		"des" : "单品营销",
		"provideMode" : "所有顾客",
		"isHaveChannel" : "yes",
		"activityObject" : "所有顾客",
		"isSupportKouBeiKe" : "yes"
	},
	"OPEN_CARD_CARE":{
		"val" : "48",
		"enum" : "OPEN_CARD_CARE",
		"DISCOUNTS_INFO" : "开卡关怀",
		"des" : "开卡关怀",
		"provideMode" : "所有顾客",
		"isHaveChannel" : "yes",
		"activityObject" : "所有顾客",
		"isSupportKouBeiKe" : "no"
	},
	"RATE_SEND" : {
		"val" : "50",
		"enum" : "RATE_SEND",
		"DISCOUNTS_INFO" : "全场折扣，提升会员到店率",
		"des" : "折扣营销",
		"provideMode" : "需要用户领取",
		"isHaveChannel" : "no",
		"activityObject" : "所有顾客",
		"isSupportKouBeiKe" : "yes"
	},
	"CROWD_SEND_FOR_CONSUME" : {
		"val" : "51",
		"enum" : "CROWD_SEND_FOR_CONSUME",
		"DISCOUNTS_INFO" : "消费送券",
		"des" : "消费送券",
		"provideMode" : "消费送券",
		"isHaveChannel" : "no",
		"activityObject" : "消费送券",
		"isSupportKouBeiKe" : "yes"
	}

};

if (App.isLogEnable) {
	document
			.write("<script type='text/javascript' src='../lib/log/log.js'></script>");
	document
			.write("<script type='text/javascript' src='../lib/log/dom.js'></script>");
	document
			.write("<script type='text/javascript' src='../lib/log/console.js'></script>");
}

var log4JS = new Log4JS();

//日志对象panjun
function Log4JS() {
	this.info = function(msg) {
		if (App.isLogEnable && typeof LogJS !== "undefined") {
			LogJS.info(msg);
		}
	};

	this.warn = function(msg) {
		if (App.isLogEnable && typeof LogJS !== "undefined") {
			LogJS.warn(msg);
		}
	};

	this.error = function(msg) {
		if (App.isLogEnable && typeof LogJS !== "undefined") {
			LogJS.error(msg);
		}
	};
}

$(function() {
	$.init && $.init();
});


//处理App硬返回逻辑
$(document).on("back",function(e){
	var $currentPage = $($.getCurrentPage());
	log4JS.info('app trigger back event,currentPage is :'+$currentPage.attr("id"));
	//共性操作
  	var oCancel = $(".confirm-cancel");
  	if(!oCancel){
  		oCancel.click();
		e.preventDefault();
		return false;
	}

  	var $loading = $(".loading");
  	if($loading.length>0){//有loading先关loading
  		common.closeLoading()
  		e.preventDefault();
  		return false;
  	}

  	var $dilogConfirm = $(".dialog-confirm");//有确认框先关确认框
  	//判断这个框是否需要关闭的条件有三个
  	//1 确认框是否显示
  	//2 是否有取消按钮
  	if($(".dialog-confirm").css("visibility") =="visible" && $dilogConfirm.length>0){
  		 $("#layer").remove();
  		 $dilogConfirm.css("visibility", "hidden").remove();
  		e.preventDefault();
  		return false;
  	}

  	if($(".mbsc-ios").length>0){
		$(".input-limited-time").mobiscroll("cancel");
    	$(".input-datetime").mobiscroll("cancel");
    	e.preventDefault();
		return false;
	}

  	//关闭模态窗口
  	if($(".actions-modal-button").size()>0){
		$.closeModal($(".actions-modal"));
		e.preventDefault();
    	return false;
    }

 	var activeNodeName = document.activeElement.nodeName.toLowerCase();
	//如果当前获得焦点的元素是input框，就说明输入框是打开的
	if(activeNodeName == 'input' || activeNodeName == 'textarea'){
		document.activeElement.blur();//这是需要先关闭输入框
		e.preventDefault();
		return false;
	}

  	//如果是top页直接退出app
  	if($currentPage.attr("topPage")=="true"){
  		AppUtil.call(AppUtil.APIS.EXIT_APP);
  		e.preventDefault();
  		return false;
  	}

	//执行当前page下的back事件
  	$currentPage.find(".back").trigger("click");
});


$(document).on("click", "a.exit-webview", function() {
	AppUtil.closeWebView();
});

var CommonUtil = {

    /**
     * 判断元素对象是否为空,undefined或者"";
     * @param obj
     * @returns {Boolean}
     */
    isNotBlank :function(obj){
    	return (obj!=undefined && obj!=null && obj!="");
    },

	/**
	 * 显示元素(由于zepto的show在有些情况下有问题，所以我们统一使用控制css的方式来实现show的功能)
	 * @param ele 元素的标识(id,className,...)
	 *
	 * <pre>
	 * 调用方式如下：
	 * showElement("#id");
	 * showElement(".className");
	 * ...
	 * </pre>
	 */
	showElement : function(ele) {
		$(ele).css("display", "block");
	},

	/**
	 * 影藏元素(由于zepto的hide在有些情况下有问题，所以我们统一使用控制css的方式来实现show的功能)
	 * @param ele 元素的标识(id,className,...)
	 *
	 * <pre>
	 * 调用方式如下：
	 * showElement("#id");
	 * showElement(".className");
	 * ...
	 * </pre>
	 */
	hideElement : function(ele) {
		$(ele).css("display", "none");
	},

	//常量：往sessionStorage中存放的paramObj的key
	CONSTANT_PARAMOBJ : "paramObj",

	/**
	 * 注入页面之间跳转需要传递的参数
	 * @paramObj 一个JSON对象，用来传递参数，其格式如下:
	 *             {"articleId":"123456"}
	 */
	injectParamObject : function(paramObj) {
		paramObj = paramObj || {};
		sessionStorage
				.setItem(this.CONSTANT_PARAMOBJ, JSON.stringify(paramObj));
	},

	/**
	 * 取出存在sessionStorage中的参数对象
	 * @return 一个JSON对象，其格式如下:
	 *  {"articleId":"123456"}
	 */
	takeOutParamObject : function() {
		var rt = sessionStorage.getItem(this.CONSTANT_PARAMOBJ);
		if (!rt) {
			return {};
		}
		return JSON.parse(rt);
	},

	/**
	 * 移除sessionStorage中的参数对象
	 */
	removeParamObject : function() {
		sessionStorage.removeItem(this.CONSTANT_PARAMOBJ);
	},

	/**
	 * 判断数组
	 * @param o
	 * @returns {boolean}
	 */
	isArray : function(o) {
		return Object.prototype.toString.call(o) === '[object Array]';
	},

	/**
	 * 获取缩略图路径
	 * @param path 原图路径
	 * @param suffix 后缀，默认_200x200
	 * @returns {string}
	 */
	getSamllPicturePath : function(path, suffix) {
		if (!path) {
			return "";
		}
		if (!suffix) {
			suffix = "_200_200";
		}
		if (path.indexOf(suffix) !== -1) {
			return path;
		}
		var paths = path.split(".");
		paths[paths.length - 2] = paths[paths.length - 2] + suffix; // 取文件名
		return paths.join(".");
	},

	/**
	 * 将对象参数转换成字符串参数a=b&c=d
	 * @param obj
	 * @returns {*}
	 */
	parseObjtoParamStr : function(obj) {
		if (obj) {
			// 返回字符串，ajax请求参数为对象的时候会对key和value都encodeURIComponent
			var params = []
			for ( var attr in obj) {
				if (obj[attr] === '') {
					continue;
				} else {
					var param = attr + "=" + obj[attr];
					params.push(param);
				}
			}

			return params.join("&");
		}
		return ""
	},

	/**
	 * 获取浏览器参数
	 * @param name
	 * @returns {null}
	 */
	getUrlParam : function(name) {
		var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
		var r = window.location.search.substr(1).match(reg);
		if (r != null)
			return decodeURI(r[2]);
		return null;
	},

	/**
	 * 自动去除数字最后的0或小数点
	 * @param num
	 * @param digit 保留小数点位数，默认2位
	 * @returns string
	 */
	fixNumber : function(num, digit) {
		if (num === "" || isNaN(num)) {
			return num;
		}
		if (typeof digit === "undefined") {
			digit = 2;
		}
		var result = parseFloat(num).toFixed(digit);
		while (result.charAt(result.length - 1) === "0") {
			result = result.substring(0, result.length - 1);
		}
		if (result.charAt(result.length - 1) === ".") {
			result = result.substring(0, result.length - 1);
		}
		return result;
	},

	/**
	 * 发送jsonp请求
	 * @param  {object} options 请求参数
	 * options.url : 请求url
	 * options.params : 请求参数对象
	 * options.success : 请求成功回调函数
	 * options.error : 请求失败回调函数（可选，包括非200以及业务错误，业务错误默认处理为弹出提示框）
	 * options.useDefaultLoading 是否使用内置的loading，默认值true
	 */
	sendJsonpRequest : function(options) {
		if (!options.params) {
			options.params = {
				sessionId : App.sessionId
			};
		} else if (typeof options.params === 'string') {
			options.params = options.params + "&sessionId=" + App.sessionId;
		} else {
			options.params.sessionId = App.sessionId;
		}


		var useDefaultLoading = options.useDefaultLoading;
		if(useDefaultLoading === undefined){
			useDefaultLoading = true;
		}

		if(useDefaultLoading === true){
			common.loading();
		}

		// log4JS.info("sendJsonpRequest start ===================================");
		// log4JS.info("url = " + options.url);
		// log4JS.info("params = " + JSON.stringify(options.params));

		$.ajax({
			"url" : options.url,
			headers : {
				sessionId : App.sessionId
			},
			async : options.async || false,
			contentType : 'application/json;charset=utf-8',
			"data" : options.params,
			"jsonp" : "callback",
			dataType : "jsonp",
			"success" : function(result) {
				if(useDefaultLoading === true){
					common.closeLoading();
				}

				// log4JS.info("success result = " + JSON.stringify(result));

				// 服务端filter重定向
				if (result && result.code == 302) {// 用户未登录
					DialogUtil.dialogWarn("用户未登录");
					//AppUtil.call(AppUtil.APIS.LOGIN);

				} else if (result && result.code == 303) {// 未关注
					DialogUtil.dialogConfirm("您无权限查看此页面");
					return true;
				} else if (result && result.code == 301) {// 没有权限
					DialogUtil.dialogConfirm("您无权限查看此页面");
					return true;
				} else {
					options.success(result);
				}
			},
			"error" : function(e) {
				if(useDefaultLoading == true){
					common.closeLoading();
				}

				log4JS.error("sendJsonpRequest error");
				DialogUtil.dialogWarn();
				if (options.error)
					options.error();
			}
		});
	},

	/**
	 * 渲染模板
	 * @param $dom jquery 对象
	 * @param templateId 模板ID
	 * @param data 数据
	 * @param isAppend 是否追加内容
	 * @param func 执行html之前的钩子 函数
	 */
	render : function($dom, templateId, data, isAppend, func) {
		if (!$dom || !templateId || !data) {
			return;
		}
		var rd = template(templateId, data); // 模板渲染完html
		func && func(); // 执行钩子函数
		if (isAppend) {
			$dom.append(rd);
		} else {
			$dom.html(rd);
		}
	},
	nullValueParser : function(targetObj, key, replaceValue) {
		return this.nullValueParserByEL(targetObj, key, replaceValue);
	},
	/**
	执行表达式并返回执行结果
	@targetObj 目标对象
	@param el 'activityDetail.activityStartTime'
	@replaceValue 如果执行表达式失败返回的结果
	 */
	nullValueParserByEL : function(targetObj, el, replaceValue) {
		if (replaceValue != 0 && !replaceValue) {
			replaceValue = '--';
		}

		var keyNames = el.split(".");
		if (keyNames.length >= 2) {
			keyNames = keyNames.splice(1);
		}

		//适配数组
		var linkedKeyNames = new Array();
		for (var i = 0; i < keyNames.length; i++) {
			if (keyNames[i].indexOf("[") != -1) {
				linkedKeyNames.push(keyNames[i].substring(0, keyNames[i]
						.indexOf("[")));
				linkedKeyNames.push(keyNames[i].substring(keyNames[i]
						.indexOf("[") + 1, keyNames[i].length - 1));
			} else {
				linkedKeyNames.push(keyNames[i]);
			}
		}

		try {
			var result = targetObj;
			for (var i = 0; i < linkedKeyNames.length; i++) {
				result = result[linkedKeyNames[i]];
			}

			if ((result != 0 && !result) || result == '') {
				result = replaceValue;
			}
		} catch (exception) {
			result = replaceValue;
		}

		return result;
	},

	/**
	    判断对象是否为空或者空字符串(多个空格也算是空字符串)
	 **/
	isEmpty : function(obj) {
		if (obj == null || obj == undefined || obj == ''
				|| obj.replace(/(^s*)|(s*$)/g, "").length == 0) {
			return true;
		} else {
			return false;
		}
	},
	getUserServiceInfo : function(){
		//先读缓存
		var userServiceInfo = sessionStorage.getItem("userServiceInfo");
		if(userServiceInfo){
			return JSON.parse(userServiceInfo);
		}

		var future = {'id':Date.now(),'finish':false,'data':'',success:''};
		var options = {
			"url":App.serverUrl + "/merchantApp/index/queryUserServiceInfo.do",
			"success":function(msg){
				future.finish = true;
				future.success = msg.success;
				future.data = msg.resultObject;

				//如果后端返回成功才写缓存
				if(msg.success){
					sessionStorage.setItem("userServiceInfo", JSON.stringify(future));
				}
			},
			"error":function(msg){
				future.finish = true;
				future.success = false;
				future.data = {};
			}
		};

		this.sendJsonpRequest(options);
		return future;
	},

	/**
	 * 部分隐藏手机号
	 * @param  {String} mobile 手机号
	 * @return {String}        中间四位星号代替
	 */
	secretShowMobile : function(mobile){
		return mobile.substr(0,3) + "****" + mobile.substr(-4);
	},
	/**
	 * 校验手机号是否合法
	 * @param mobile
	 * @returns {boolean}
	 */
	checkMobile : function (mobile) {
		if (!mobile) {
			return false;
		}
		if(mobile.length<11){
			return false;
		}
		if(mobile.length>11){
			return false;
		}
		if(isNaN(mobile)){
			return false;
		}
		if (new RegExp(/^1\d{10}$/).test(mobile)) {
			return true;
		}
		return false;
	},

	/**
	 * 计算字符串字节数
	 * @param  {String} str 计算的字符串
	 * @param  {[int]} size4Chinese   每个汉字代表字节数
	 * @return {[int]}     字节总数
	 */
	countBytes : function(str,size4Chinese){
		var str4Single = str.replace(/[\u4e00-\u9fa5]+/g,"");
		var str4Chinese = str.replace(/[^\u4e00-\u9fa5]+/g,"");
		return str4Single.length + str4Chinese.length * size4Chinese;
	}
};

/*弹窗工具类*/
DialogUtil = {
	/**
	 * 提示公共方法,警告提示信息;
	 * @param func;回调函数;
	 * @param time 显示时间，ms 默认3s
	 * @param msg 提示信息
	 */
	dialogWarn : function(msg, func, time) {
		if (!msg) {
			msg = "无法连接网络，请检查网络设置后重试";
		}
		var jsonParam = {};
		jsonParam.text = msg;
		jsonParam.class = "dialog-warn";
		jsonParam.time = time || 3000;
		if (func) {
			jsonParam.callback = func;
		}
		common.dialog(jsonParam);
	},

	/**
	 * 提示公共方法,成功信息提示;
	 * @param msg
	 * @param func;回调函数;
	 * @param time 显示时间，ms 默认3s
	 */
	dialogSuccess : function(msg, func, time) {
		if (!msg) {
			msg = "处理成功!";
		}
		var jsonParam = {};
		jsonParam.text = msg;
		jsonParam.class = "dialog-success";
		jsonParam.time = time || 3000;
		if (func) {
			jsonParam.callback = func;
		}
		common.dialog(jsonParam);

	},

	/**
	 * 确认弹窗;
	 * @param jsonParam:必须json格式或者string;
	 */
	dialogConfirm : function(jsonParam) {
		if (typeof jsonParam === "string") {
			var param = {
				title : "",
				content : jsonParam,
				btnLeft : "知道了"
			};
			common.confirm(param);
		} else {
			common.confirm(jsonParam);
		}
	}
};

/**活动相关工具类*/
ActivityUtil = {

     /**加载时间控件,活动时间联动;*/
	  loadTimeWidget : function(isRefresh,func){
	    	 var isCallBack = false;
	    	 if(isRefresh){
	    		 isCallBack = isRefresh;
	    	 }
	    	 if(func){
	    		 func();
	    	 }
	    	 var dateType = createActivityPublicParam.selectDateParams.dateType;
	         var currYear = new Date().getFullYear();
	         var beginMaxDate =new Date(new Date().setFullYear(new Date().getFullYear() + 2));
	         var beginMinDate = new Date(new Date().setFullYear(currYear));
	         var endMaxDate = DateUtil.addDays(DateUtil.str2Date((dateType=="activityDate")?createActivityPublicParam.activityStartTime:createActivityPublicParam.voucherStartTime),364);
	         var endMinDate = DateUtil.str2Date((dateType=="activityDate")?createActivityPublicParam.activityStartTime:createActivityPublicParam.voucherStartTime);
			 var beginDateParams = {
			    "pageId":createActivityPublicParam.selectDateParams.pageId,
			    "inputDateId":createActivityPublicParam.selectDateParams.beginDateInputId,
				"defaultValue" : DateUtil.str2Date((dateType=="activityDate")?createActivityPublicParam.activityStartTime:createActivityPublicParam.voucherStartTime),
				"maxDate" : beginMaxDate,
				"minDate" : beginMinDate,
				"selectEvent" :createActivityPublicParam.selectDateParams.selectBeginDateFunc
	         }, endDateParams = {
			    "pageId":createActivityPublicParam.selectDateParams.pageId,
			    "inputDateId":createActivityPublicParam.selectDateParams.endDateInputId,
				"defaultValue" : DateUtil.str2Date((dateType=="activityDate")?createActivityPublicParam.activityEndTime:createActivityPublicParam.voucherEndTime),
				"maxDate" : endMaxDate,
				"minDate" : endMinDate,
				"selectEvent" : createActivityPublicParam.selectDateParams.selectEndDateFunc
			 };
	    	 // 这里检查上面异步回调函数结果,间隔100毫秒;
	    	 var sh;
	    	 sh=setInterval(function(){
	    		 if(isCallBack){
	    			try{
	    				DateUtil.initDateTimeWidget(beginDateParams);
	    				DateUtil.initDateTimeWidget(endDateParams);
	    				clearInterval(sh);
	    			}catch(err){
	    			    clearInterval(sh);
	    			}
	    		 }
	    	 },100);

	 },

	/**
	 * 只在页面首次初始化时候调用;
	 * 根据活动类型控制创建活动页面标签是否现实隐藏;
	 */
	controlPageLabel : function(pageId, actTypeId) {
		var act = this.getActivityByType(actTypeId);
		var act_enum_val = act.enum;
		//设置头部title标题;
		$("#" + pageId + " .middle").text(act.des);
		//设置页面导航显示;
		if(actTypeId == ACTIVITY_TYPE.ITEM_MARKET.val || actTypeId == ACTIVITY_TYPE.LATTER_SEND.val){
			 $("#" + pageId + " .process-wrap").removeClass("hide");
			 $("#" + pageId + " .quan-area").addClass("hide");
		}else{
			 $("#" + pageId + " .process-wrap").addClass("hide");
		}
		//显示活动基础属性标签控制;
		$("#" + pageId + " .activity-setting .item-list").find("li").each(function() {
					if ($(this).attr("showAct") != null) {
						if ($(this).attr("showAct").indexOf(act_enum_val) != -1 || $(this).attr("showAct") == "ALL") {
							$(this).removeClass("hide");
						} else {
							$(this).addClass("hide");
						}
					}
        });
		if(act.isHaveChannel == "yes"){//有渠道的活动;
			var isGoldUser = false;//默认为银元宝;
		    if(createActivityPublicParam.userServiceVersion && createActivityPublicParam.userServiceVersion == 1){
		    	isGoldUser = true;//金员宝;
		    }
			var _$LiElts = [];
			var _$channels = $("#" + pageId + " #channels").find("li");
			if(_$channels!=undefined && _$channels!=null && _$channels.length>0){
				 _$channels.each(function(){
					   _$LiElts.push($(this));
					   if ($(this).attr("showAct") != null) {
							if ($(this).attr("showAct").indexOf(act_enum_val) != -1 || $(this).attr("showAct") == "ALL") {
								if($(this).attr("channel_val")=="POS"){
									if(isGoldUser){//金员宝需要显示收银二维码;
										$(this).removeClass("hide");
									}else{
										$(this).addClass("hide");
									}
								}else{
									$(this).removeClass("hide");
								}

							} else {
								$(this).addClass("hide");
							}
						}

				 });
			}
			if(_$LiElts.length == 0){
				return;
			}
			if(actTypeId !=ACTIVITY_TYPE.OPEN_CARD_CARE.val || actTypeId !=ACTIVITY_TYPE.SCAN_CODE.val){
				_$LiElts[0].addClass("checked disabled");
			}
			if(isGoldUser){//金元宝商户;
				if(actTypeId ==ACTIVITY_TYPE.SCAN_CODE.val){
					_$LiElts[2].addClass("checked disabled");
				}else{
					_$LiElts[2].addClass("checked");
				}
			}

			//活动对应渠道默认勾选状态显示控制;渠道0=支付宝;渠道1=收银吗;渠道2=收银小票;渠道3=口碑客;
			var checkedChannelsLen =createActivityPublicParam.channelType.length;
			if(checkedChannelsLen>0){
				for(var i=0;i<_$LiElts.length;i++){
					if(_$LiElts[i].attr("class").indexOf("disabled")==-1){
						if(this.isCheckedChannel(_$LiElts[i].attr("channel_val"))==false){
							_$LiElts[i].removeClass("checked");
						}else{
							_$LiElts[i].removeClass("checked").addClass("checked");
						}
					}
				}
			}
		}

	},

	isCheckedChannel : function(channelVal){
		var currentCheckedChannels = createActivityPublicParam.channelType;
		for(var i=0;i<currentCheckedChannels.length;i++){
			if(channelVal == currentCheckedChannels[i]){
				return true;
			}
		}
		return false;
	},


	/**
	 * 是否存在该活动类型Id;存在返回true;
	 */
	isExistActivity : function(actTypeId) {
		for ( var k in ACTIVITY_TYPE) {
			if (actTypeId == ACTIVITY_TYPE[k].val) {
				return true;
			}
		}
		return false;

	},

	/**
	 * 根据活动类型Id，获取活动类型结构体;
	 */
	getActivityByType : function(actTypeId) {
		for ( var k in ACTIVITY_TYPE) {
			if (actTypeId == ACTIVITY_TYPE[k].val) {
				return ACTIVITY_TYPE[k];
			}
		}
		return null;
	},
	/** 针对阶梯和优惠券安装不同规则进行排序; */
	 sortDiscountDataArray:function(jsonObj){
	 	 if(jsonObj==null||jsonObj.length==0){
	 		 return [];
	 	 }
	      var temp;
	      for(i=0;i<jsonObj.length;i++){
		        if((i+1)<jsonObj.length){
		          	 if(Number(jsonObj[i].receiveConditionMoney) > Number(jsonObj[i+1].receiveConditionMoney)){
				      temp = jsonObj[i];
				      jsonObj[i] = jsonObj[i+1];
				      jsonObj[i+1] = temp;
				      this.sortDiscountDataArray(jsonObj);
			         }

		        }

	     }
	     return jsonObj;
	 },

	/**
	 * 比较两个json对象是否相同;
	 */
	compareObj : function(obj1, obj2) {
		if (obj1 == null || obj2 == null) {
			return false;
		}
		if (JSON.stringify(obj1) == JSON.stringify(obj2)) {
			return true;
		}
		return false;

	},

	/**
	 * 将活动状态转换成中文
	 * @param status
	 */
	parseActivityStatus2Ch : function(status) {
		if (status === undefined || status === null) {
			return "未知";
		}
		switch (status) {
		case -1:
			return "创建中";
		case -2:
			return "创建失败";
		case 1:
			return "未开始";
		case 2:
			return "进行中";
		case 3:
			return "已结束";
		case 4:
			return "待确认";
		case 5:
			return "已终止";
		case 6:
			return "终止中";
		case 7:
			return "创建中-待确认";
		case 8:
			return "商家驳回";
		case 9:
			return "终止中-待确认";
		case 10:
			return "审核中";
		case 11:
			return "审核驳回";
		case 12:
			return "已终止";
		case 13:
			return "已终止";
		case 14:
			return "终止中";
		case 15:
			return "终止中";
		case 16:
			return "终止中-待确认";
		case 17:
			return "终止中-待确认";
		case 18:
			return "修改中";
		case 19:
			return "修改中";
		case 20:
			return "修改中-待确认";
		case 21:
			return "修改中-待确认";
		case 22:
			return "活动失效";

		default:
			return "未知";
		}

	},

	/**
	 * 拼装优惠券名字
	 * @param promTool
	 * @returns {*}
	 */
	parseVoucherName : function(promTool) {
		if (!promTool) {
			return "未知";
		}
		if (promTool.voucherType === "MONEY") {
			if (promTool.moneyVoucherType == 1) {
				// 全场代金券
				return promTool.voucherWorthValue + "元全场代金券";
			} else {
				// 单品券
				return promTool.voucherWorthValue + "元"
						+ (promTool.voucherItem ? promTool.voucherItem.itemName : "单品") + "代金券";
			}
		} else if (promTool.voucherType === "RATE") {
			return promTool.voucherRate * 10 + "折折扣券";
		} else {
			return promTool.voucherName;
		}
	}
};

/**
 * 工具类:提供全局公用方法；
 * @autho
 * r: panjun7;
 */

DateUtil = {
      /**初始化活动日期事件*/
      initDateTimeWidget:function(params){
	    	 if(params&&!params.selectEvent){
	    		 params.selectEvent = function(){};
	    	 }
	    	 $("#"+params.pageId+" #"+params.inputDateId).mobiscroll().date({
	             theme: 'ios',
	             model: 'scroller',
	             lang: 'zh',
	             display: 'bottom',
	             dateFormat: 'yy-mm-dd',
	             defaultValue: params.defaultValue,
	             maxDate: params.maxDate,
	             minDate: params.minDate,
	             onSelect:params.selectEvent
	         });

	},
   /**字符串日期转换为Date;*/
    str2Date :function (dateStr){
	        var dr = dateStr.split("-");
	        return new Date((dr[0]),(parseInt(dr[1])-1),(dr[2]))
	},
    /**
    获取日期的YYYYMMDD格式
    */
    getDateYYYYMMDD : function(date){
        // var year = date.getFullYear();
        // var month = date.getMonth()+1;
        // var day = date.getDate();
        // if(month < 10){
        //     month = "0"+month;
        // }
        // if(day < 10){
        //     day = "0"+day;
        // }

        // return  year + "" + month +"" + day;

        return this.format(date,"yyyyMMdd");
    },
    getDateYYYYMM : function(date){
        return this.format(date,"yyyyMM");
	},
	getDateTime : function(date){
        return this.format(date);
    },
    /**
    获取日期的YYYY-MM-DD格式
    **/
    getDateFormat : function(date){
        var year = date.getFullYear();
        var month = date.getMonth()+1;
        var day = date.getDate();
        if(month < 10){
            month = "0"+month;
        }
        if(day < 10){
            day = "0"+day;
        }

        return  year + "-" + month +"-" + day;
    },
    /**
    翻日历
    */
    addDays:function(date,days){
        var time = date.getTime();
        var addTimes = days*24*3600*1000;
        date.setTime(time+addTimes);
        return date;
    },

    /**
	 * @param date 时间，Date or 时间戳，默认当前时间
	 * @param pattern 转换格式，默认yyyy-MM-dd hh:mm:ss
	 * @return string
	 *
    <p>对Date的扩展，将 Date 转化为指定格式的String
    月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符，
    年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
    例子：
    (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
    (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18</p>
    */
    format:function(date,pattern){

        Date.prototype.Format = function (fmt) { //author: meizz
            var o = {
                "M+": this.getMonth() + 1, //月份
                "d+": this.getDate(), //日
                "h+": this.getHours(), //小时
                "m+": this.getMinutes(), //分
                "s+": this.getSeconds(), //秒
                "q+": Math.floor((this.getMonth() + 3) / 3), //季度
                "S": this.getMilliseconds() //毫秒
            };
            if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
            for (var k in o)
            if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
            return fmt;
        };

        if (!pattern) {
        	pattern = "yyyy-MM-dd hh:mm:ss";
		}
        if (!date) {
        	date = new Date();
		}
        if (typeof date === "number") {
        	return new Date(date).Format(pattern);
		} else {
            return date.Format(pattern);
        }
    },

    compareDate:function(datestr1, datestr2) {
        return Date.parse(datestr1.replace(/-/g, "/")) > Date.parse( datestr2.replace(/-/g, "/"));
    //     var date1 = new Date(Date.parse(datestr1.replace(/-/g, "/")));
    //     var date2 = new Date(Date.parse(datestr2.replace(/-/g, "/")));
    //  
    //     if (date1.getTime() > date2.getTime()) {
    //         return false;
    //     }else{
    //         return true;
    //     }
    }

};

//常量
Constants = {

    //门店相关
    "store" : {

        //套餐类型
        "SERVICE_VERSION_TYPE" : {
            "none" : "0",   //未订购
            "gold" : "1",   //金员宝
            "silver" : "2", //银员宝
            "cloud_share_pay" : "-1" //快享付
        },
        "getServiceVersionTypeText" : function(serviceVersionType){
            if(serviceVersionType == this.SERVICE_VERSION_TYPE.none){
                return "未订购";
            }else if(serviceVersionType == this.SERVICE_VERSION_TYPE.gold){
                return "金员宝";
            }else if(serviceVersionType == this.SERVICE_VERSION_TYPE.silver){
                return "银员宝";
            }else if(serviceVersionType == this.SERVICE_VERSION_TYPE.cloud_share_pay){
                return "快享付";
            }else{
                return "未知";
            }
        },

        //口碑状态
        "KOUBEI_STATUS" : {
            "online" : "T", //上架
            "offline" : "F" //下架
        },
        "getKoubeiStatus" : function(koubeiStatus){
            if(koubeiStatus == this.KOUBEI_STATUS.online){
                return "正常";
            }else if(koubeiStatus == this.KOUBEI_STATUS.offline){
                return "下架";
            }else{
                return "未知";
            }
        },

		//订购状态
		"SUBSCRIBE_STATUS" : {
			"none" : "0", //未订购
			"normal" : "1", //正常
			"refund" : "2", //已退订
			"expire" : "3" //已过期
		},
		"getSubscribeStatus" : function(subscribeStatus) {
			if (subscribeStatus == this.SUBSCRIBE_STATUS.none) {
				return "未订购";
			} else if (subscribeStatus == this.SUBSCRIBE_STATUS.normal) {
				return "正常";
			} else if (subscribeStatus == this.SUBSCRIBE_STATUS.refund) {
				return "已退订";
			} else if (subscribeStatus == this.SUBSCRIBE_STATUS.expire) {
				return "已过期";
			} else {
				return "未知";
			}
		},

		//支付宝开通状态
		"ALI_PAY_STATUS" : {
			"none" : "0", //未开通
			"open" : "1" //已开通
		},
		"getAlipayOpenStatus" : function(aliPayStatus) {
			if (aliPayStatus == this.ALI_PAY_STATUS.none) {
				return "未开通";
			} else if (aliPayStatus == this.ALI_PAY_STATUS.open) {
				return "已开通";
			} else {
				return "未知";
			}
		},

		//微信支付开通状态
		"WEIXIN_PAY_STATUS" : {
			"none" : "0", //未开通
			"doing" : "3" , //开通中
			"open" : "1", //已开通
			"frozen" : "2" //已冻结
		},
		"getWeixinPayStatus" : function(weixinPayStatus) {
			if (weixinPayStatus == this.WEIXIN_PAY_STATUS.none) {
				return "未开通";
			}else if (weixinPayStatus == this.WEIXIN_PAY_STATUS.open) {
				return "已开通";
			}else if (weixinPayStatus == this.WEIXIN_PAY_STATUS.frozen) {
				return "已冻结";
			}else if(weixinPayStatus == this.WEIXIN_PAY_STATUS.doing){
				return "开通中";
			}else {
				return "未知";
			}
		},

		//快享付状态
		"CLOUD_SHARE_PAY_STATUS" : {
			"unOpen" : "1_0" , //未开通
			"wait2OpenWeixin" : "1_1" , //待开通微信支付
			"wait2Activate" : "1_2" , //收款码待激活
			"opened" : "1_3" //已开通
		},
		"getCloudSharePayStatusText" : function(cloudSharePayStatus){
			if(cloudSharePayStatus == this.CLOUD_SHARE_PAY_STATUS.unOpen){
				return "未开通";
			}else if(cloudSharePayStatus == this.CLOUD_SHARE_PAY_STATUS.wait2OpenWeixin){
				return "待开通微信收款";
			}else if(cloudSharePayStatus == this.CLOUD_SHARE_PAY_STATUS.wait2Activate){
				return "收款码待激活";
			}else if(cloudSharePayStatus == this.CLOUD_SHARE_PAY_STATUS.opened){
				return "已开通";
			}else{
				return "未知";
			}
		},

		//银联开通状态
		"UNION_PAY_STATUS" : {
			"unOpen" :  "0" , //未开通
			"opening" : "1" , //申请中
			"open" : "2" //已开通
		},
		"getUnionPayStatusText" : function(unionPayStatus){
			if(unionPayStatus == this.UNION_PAY_STATUS.unOpen){
				return "未开通";
			}else if(unionPayStatus == this.UNION_PAY_STATUS.opening){
				return "申请中";
			}else if(unionPayStatus == this.UNION_PAY_STATUS.opened){
				return "已开通";
			}else {
				return "未知";
			}
		},

		//微信渠道
		"WEIXIN_CHANNEL" : {
			"none" : "0" , 	//暂未开通（优先走网商渠道）
			"weifutong" : "2" , //威富通
			"wangshang" : "1" //网商
		},
		"getWeixinChannelText" : function(weixinChannel){
			if(weixinChannel == this.WEIXIN_CHANNEL.weifutong){
				return "中信";
			}else if(weixinChannel == this.WEIXIN_CHANNEL.wangshang){
				return "网商";
			}else{
				return "未知渠道";
			}
		}
	},
	"activity" : {
        "getActivityName" :function (activityType) {
        	switch (activityType) {
               case "22": return "消费送券";
               case "25": return "扫码送券";
               case "35": return "消费送券";
               case "43": return "挽回流失会员";
               case "46": return "新会员招募";
               case "47": return "单品营销";
               case "48": return "开卡关怀";
               case "51": return "消费送券";
               default: return "未知活动类型";
            }
        }
    },

    //开通微信支付相关
    "weixin" : {

    	//行业类别
    	"INDUSTRY_TYPE" : {
    		// "person" : "212",  //个体工商户-餐饮
			// "company" : "135" //企业-餐饮
			'01':'01',
			'02':'02',
			'03':'03'
    	},
    	"getIndustryTypeText" :function(industryType){
    		if(industryType == this.INDUSTRY_TYPE.person){
    			return "个体工商户-餐饮";
    		}else if(industryType == this.INDUSTRY_TYPE.company){
				return "企业-餐饮";
			}else if(industryType == this.INDUSTRY_TYPE["01"]){
    			return "自然人";
    		}else if(industryType == this.INDUSTRY_TYPE["02"]){
    			return "个体工商户";
    		}else if(industryType == this.INDUSTRY_TYPE["03"]){
    			return "企业商户";
    		}else{
    			return "未知";
    		}
    	},

    	//账户类型
    	"ACCOUNT_TYPE" : {
    		"person" : "1",  //个人账户
    		"company" : "2" //企业账户
    	},
    	"getAccountTypeText" : function(accountType){
    		if(accountType == this.ACCOUNT_TYPE.person){
    			return "个人账户";
    		}else if(accountType == this.ACCOUNT_TYPE.company){
    			return "企业账户";
    		}else{
    			return "未知";
    		}
    	},

    	//变更状态
    	"MODIFY_STATUS" : {
    		"auditing" : "1",  //审核中
    		"success" : "2", //变更成功
    		"error" : "3" //变更失败
    	},
    	"getModifyStatus" : function(modifyStatus){
    		if(modifyStatus == this.MODIFY_STATUS.auditing){
    			return "审核中";
    		}else if(modifyStatus == this.MODIFY_STATUS.success){
    			return "变更成功";
    		}else if(modifyStatus == this.MODIFY_STATUS.error){
    			return "变更失败";
    		}else{
    			return "未知变更状态";
    		}
    	},

    	//微信账户操作
    	"OPERATE_TYPE" : {
    		"add" : "1",	//新增
    		"edit" : "2"	//编辑
    	}
    },

    //微信支付开通（网商）
    "weixin_wangshang" : {

    	//账户类型
    	"ACCOUNT_TYPE" : {
    		"person" : "01",  //个人账户
    		"company" : "02" //企业账户
    	},
    	"getAccountTypeText" : function(accountType){
    		if(accountType == this.ACCOUNT_TYPE.person){
    			return "对私账户";
    		}else if(accountType == this.ACCOUNT_TYPE.company){
    			return "对公账户";
    		}else{
    			return "未知";
    		}
    	},

    	//开通状态
    	"WEIXIN_PAY_STATUS" : {
    		"none" : "0", //未开通
    		"auditing" : "3" , //审核中
    		"open" : "1", //已开通
    		"failture" : "5", //开通失败
    		"closed" : "4" 	//关闭
    	},
    	"getWeixinPayStatus" : function(weixinPayStatus) {
    		if (weixinPayStatus == this.WEIXIN_PAY_STATUS.none) {
    			return "未开通";
    		}else if (weixinPayStatus == this.WEIXIN_PAY_STATUS.auditing) {
    			return "审核中";
    		}else if (weixinPayStatus == this.WEIXIN_PAY_STATUS.open) {
    			return "已开通";
    		}else if(weixinPayStatus == this.WEIXIN_PAY_STATUS.failture){
    			return "开通失败";
    		}else if(weixinPayStatus == this.WEIXIN_PAY_STATUS.closed){
    			return "关闭";
    		}else {
    			return "未知";
    		}
    	},
    	"MERCHANT_TYPE" : {
    		"nature_person" : "01", //自然人
    		"person_business" : "02" , //个体工商户
    		"enterprise_business" : "03"  //企业商户
    	},

    	//商户类型
    	"getMerchantTypeText" : function(merchantType){
    		if(merchantType == this.MERCHANT_TYPE.nature_person){
    			return "自然人";
    		}else if(merchantType == this.MERCHANT_TYPE.person_business){
    			return "个体工商户";
    		}else if(merchantType == this.MERCHANT_TYPE.enterprise_business){
    			return "企业商户";
    		}else{
    			return "未知商户类型";
    		}
    	},

    	//经营范围
    	"BUSINESS_RANGE" : {
    		"food" : "2015050700000000" , //美食
    		"market" : "2015091000052157" , //超市便利店
    		"entertainment" : "2015062600004525" , //休闲娱乐
    		"shopping" : "2015062600002758" , //购物
    		"car" : "2016062900190124" , //爱车
    		"life" : "2015063000020189" , //生活服务
    		"education" : "2016042200000148" , //教育培训
    		"medical" : "2016062900190296" , //医疗健康
    		"tourism" : "2015080600000001" , //航旅
    		"sale" : "2016062900190337" , //专业销售/批发
    		"government" : "2016062900190371" //政府/社会组织
    	},
    	"getBusinessRangeText" : function(businessType){
    		if(businessType == this.BUSINESS_RANGE.food){
    			return "美食";
    		}else if(businessType == this.BUSINESS_RANGE.market){
    			return "超市便利店";
    		}else if(businessType == this.BUSINESS_RANGE.entertainment){
    			return "休闲娱乐";
    		}else if(businessType == this.BUSINESS_RANGE.shopping){
    			return "购物";
    		}else if(businessType == this.BUSINESS_RANGE.car){
    			return "爱车";
    		}else if(businessType == this.BUSINESS_RANGE.life){
    			return "生活服务";
    		}else if(businessType == this.BUSINESS_RANGE.education){
    			return "教育培训";
    		}else if(businessType == this.BUSINESS_RANGE.medical){
    			return "医疗健康";
    		}else if(businessType == this.BUSINESS_RANGE.tourism){
    			return "航旅";
    		}else if(businessType == this.BUSINESS_RANGE.sale){
    			return "专业销售/批发";
    		}else if(businessType == this.BUSINESS_RANGE.government){
    			return "政府/社会组织";
    		}
    	},

    	//图片类型
    	"PCITURE_TYPE" : {
    		"idcard_front" : "01",	//身份证正面
    		"idcard_back" : "02",	//身份证反面
    		"business_lisence" : "03",	//营业执照
    		"account_lisence" : "05"	//开户许可证
    	}

    }
}

/**
 * 城市相关工具方法
 * @type {Object}
 */
CityUtil = {

	//ul标签缓存
	_cache : {"provinceCityAreaHtml" : "" , "provinceCityHtml" : ""},

	/**
	 * 加载本地基础数据
	 * @param  {Function} callback 回调
	 */
	_getBaseData : function(callback){
		$.ajax({
			"method" : "GET",
			"url" : "../lib/cityInfo.json",
			"dataType" : "json",
			"success" : function(result){
				var data = result.cityJson;
				callback(data);
			}
		});
	},

	/**
	 * 渲染html
	 * @param  {[type]} data  基础数据
	 * @param  {[type]} level 渲染层级（1：省 2：省-市 3：省-市-区）
	 */
	_renderHtml : function(data,level){

		//构造树
		var $tree = $("<ul style='display:none;'></ul>");
		$.each(data,function(index,element){
			if(element.item_code.substr(-4) == "0000" && level >= 1){//省
				$tree.append("<li id='province_"+element.item_code+"' data-code='"+element.item_code+"' data-val='"+element.item_name+"'>"+element.item_name+"</li>");
			}else if(element.item_code.substr(-2) == "00" && level >= 2){//市
				var $province = $tree.find("#province_"+element.item_code.substr(0,2) + "0000");
				if($province.children("ul").length == 0){
					$province.append("<ul></ul>");
				}
				$province.children("ul").append("<li id='city_"+element.item_code+"' data-code='"+element.item_code+"' data-val='"+element.item_name+"'>"+element.item_name+"</li>");
			}else if(level == 3){//区
				var $city = $tree.find("#city_"+element.item_code.substr(0,4) + "00");
				if($city.children("ul").length == 0){
					$city.append("<ul></ul>");
				}
				$city.children("ul").append("<li id='district_"+element.item_code+"' data-code='"+element.item_code+"' data-val='"+element.item_name+"'>"+element.item_name+"</li>");
			}

		});

		//输出html
		var html = "";
		html = $("<div></div>").append($tree).html();
		return html;
	},

	/**
	 * 省市通用Html
	 * @param  {Function} callback 回调
	 */
	getProvinceCityHtml : function(callback){
		if(this._cache.provinceCityHtml){
			callback(this._cache.provinceCityHtml);
		}else{
			var self = this;
			this._getBaseData(function(data){
				var html = CityUtil._renderHtml(data,2);
				self._cache.provinceCityHtml = html;
				callback(html);
			});
		}
	},

	/**
	 * 省市区通用Html
	 * @param  {Function} callback 回调
	 */
	getProviceCityAreaHtml : function(callback){
		if(this._cache.provinceCityAreaHtml){
			callback(this._cache.provinceCityAreaHtml);
		}else{
			var self = this;
			this._getBaseData(function(data){
				var html = CityUtil._renderHtml(data,3);
				self._cache.provinceCityAreaHtml = html;
				callback(html);
			});
		}
	}
};

//获取sessionId和登录用户信息
App.sessionId = CommonUtil.getUrlParam("s") || App.sessionId;
if(!App.urlParam){
	App.urlParam=window.location.href.split("?")[1];
}
var serverUrl = CommonUtil.getUrlParam("url")||App.serverUrl;
serverUrl = decodeURIComponent(serverUrl);
if(serverUrl&&serverUrl !==''){
	App.serverUrl = serverUrl;
}
var loginUser = {};
function getLoginUser(){
	CommonUtil.sendJsonpRequest({
		"url" : App.serverUrl+"/app/employee/info.do",
		"params" : {},
		"success" : function(result){
			if(result.success.toString() == "true"){//success
				loginUser = result.resultObject;
			}else{//business error
				DialogUtil.dialogWarn("获取登录用户信息：" + result.msg);
			}
		},
		"error" : function(){//not 200
			DialogUtil.dialogWarn("获取登录用户信息：请求失败，请稍候重试");
		},
		"useDefaultLoading":false
	});
}
getLoginUser();
(function () {
    /**
     * 动态加载js文件
     * @param  {string}   url      js文件的url地址
     * @param  {Function} callback 加载完成后的回调函数
     */
    var _getScript = function (url, callback) {
        var head = document.getElementsByTagName('head')[0],
            js = document.createElement('script');

        js.setAttribute('type', 'text/javascript');
        js.setAttribute('src', url);

        head.appendChild(js);

        //执行回调
        var callbackFn = function () {
            if (typeof callback === 'function') {
                callback();
            }
        };

        if (document.all) { //IE
            js.onreadystatechange = function () {
                if (js.readyState == 'loaded' || js.readyState == 'complete') {
                    callbackFn();
                }
            }
        } else {
            js.onload = function () {
                callbackFn();
            }
        }
    }

    //如果使用的是zepto，就添加扩展函数
    if (Zepto) {
        $.getScript = _getScript;
    }
	if(App.isNewConsole){
		$.getScript("../lib/vconsole.min.js",function(){
			var vConsole = new VConsole();
		});
	}
})();
